package com.hfi.security.app.social;

import com.hfi.security.core.exception.ErrorCode;
import com.hfi.security.core.social.SocialUserInfo;
import com.hfi.security.core.support.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ChangLiang
 * @date 2019/9/3
 */
@RestController
public class AppSignUpController {

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @Autowired
    private AppSignUpUtils appSignUpUtils;

    @GetMapping("/social/signUp")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Response getSocialUserInfo(HttpServletRequest request) {
        Response resp = new Response();
        ErrorCode result = ErrorCode.OK;
        SocialUserInfo socialUserInfo = null;
        try {
            socialUserInfo = new SocialUserInfo();
            Connection<?> connectionFromSession =
                    providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
            socialUserInfo.setProviderId(connectionFromSession.getKey().getProviderId());
            socialUserInfo.setProviderUserId(connectionFromSession.getKey().getProviderUserId());
            socialUserInfo.setNickname(connectionFromSession.getDisplayName());
            socialUserInfo.setHeadImg(connectionFromSession.getImageUrl());
            // 把第三方用户信息存储到redis中
            appSignUpUtils.saveConnectionDate(new ServletWebRequest(request),connectionFromSession.createData());
            resp.setData(socialUserInfo);
        } catch (Exception e) {
            result = ErrorCode.ERROR;
        }
        resp.setErrorcode(result.value);
        resp.setValue(result.memo);
        return resp;
    }
}
